package fr.uha.ensisa.kfetmanager.admin;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author JC
 */
public class AdminPasswordChange extends HttpServlet {

    private final String errorPage = "/error.jsp";
    private final String redirectTo = "/admin/password";

    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        getServletContext().getRequestDispatcher("/admin/AdminPassword.jsp").forward(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String oldPass = request.getParameter("oldPass");
        String newPass = request.getParameter("newPass");
        String newPassRepeat = request.getParameter("newPassRepeat");

        boolean parametersOk = false;
        String errorMessage = "";

        if (oldPass == null || newPass == null || newPassRepeat == null
                || oldPass.isEmpty() || newPass.isEmpty() || newPassRepeat.isEmpty()) {
            errorMessage = "Un champ n'a pas &eacute;t&eacute; rempli.";
        } else if (!oldPass.equals(getServletContext().getAttribute("password"))) {
            errorMessage = "Le mot de passe n'est pas correct. ";
        } else if (!newPass.equals(newPassRepeat)) {
            errorMessage = "Les nouveaux mots de passe ne correspondent pas.";
        } else {
            parametersOk = true;
        }

        if (!parametersOk) {
            getServletContext().setAttribute("errorMessage", errorMessage);
            getServletContext().setAttribute("redirectTo", redirectTo);
            getServletContext().getRequestDispatcher(errorPage).forward(request, response);
            return;
        }

        getServletContext().setAttribute("password", newPass);
        getServletContext().getRequestDispatcher("/admin/AdminPassword.jsp").forward(request, response);
    }
}
